//
//  UIColor.swift
//  reactsdk
//
//  Created by Валиева Анна Евгеньевна on 02.04.2024.
//

import UIKit

extension UIColor {

  convenience init?(hex: String?) {
    guard let hex = hex?.trimmingCharacters(in: CharacterSet.alphanumerics.inverted).uppercased() else { return nil }

    var int = UInt64()
    Scanner(string: hex).scanHexInt64(&int)

    let alpha, red, green, blue: UInt64

    switch hex.count {
    case 3:
      (alpha, red, green, blue) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6:
      (alpha, red, green, blue) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8:
      (alpha, red, green, blue) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
      (alpha, red, green, blue) = (255, 0, 0, 0)
    }

    self.init(red: CGFloat(red) / 255,
          green: CGFloat(green) / 255,
          blue: CGFloat(blue) / 255,
          alpha: CGFloat(alpha) / 255)
  }
}
